package com.environment_pro.monitor.scheduler.job;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.text.DecimalFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.environment_pro.monitor.util.StaticUtil;

/**
 * 输出系统运行时信息 轮训
 * @author yangfeng
 *
 */
public class RuntimeInfoJob implements Job{
	
	private static final Logger logger = Logger.getLogger(RuntimeInfoJob.class);
	
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		logger.info("JobKey:"+arg0.getJobDetail().getKey());
		// Get JVM's system info
		RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
	    Date startDate = new Date( bean.getStartTime()); //启动时间   
	    long upTime = (bean.getUptime()/1000/60/60);  //运行时长
	    //String jvmName =bean.getName();            //JVM名称
	    
	    logger.debug("RuntimeMXBean.StartTime:"+StaticUtil.date2String(startDate));
	    logger.debug("RuntimeMXBean.Uptime:"+upTime+"H");

	  	// Get JVM Thread Info
		ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
		int threadCount = threadBean.getThreadCount();
		int daemonThreadCount =threadBean.getDaemonThreadCount();
		int peakThreadCount =threadBean.getPeakThreadCount();
		long totalStartedThreadCount =threadBean.getTotalStartedThreadCount();
		
		logger.debug("ThreadMXBean.ThreadCount:"+threadCount);
		logger.debug("ThreadMXBean.daemonThreadCount:"+daemonThreadCount);
		logger.debug("ThreadMXBean.peakThreadCount:"+peakThreadCount);
		logger.debug("ThreadMXBean.totalStartedThreadCount:"+totalStartedThreadCount);
	    
		// The java runtime Memory
		Runtime runtime = Runtime.getRuntime();
		double freeMemory = (double) runtime.freeMemory() / (1024 * 1024);
		double totalMemory = (double) runtime.totalMemory() / (1024 * 1024);
		double percentFree = ((double) freeMemory / (double) totalMemory);
		
		DecimalFormat    decimalFormat   = new DecimalFormat("######0.0"); 
		
		logger.info("Runtime.freeMemory/totalMemory:"+decimalFormat.format(freeMemory)+"M/"
				+decimalFormat.format(totalMemory)+"M, percentFree:"
				+decimalFormat.format(percentFree*100)+"%");
		if(percentFree<0.3){
			logger.warn("Runtime.freeMemory "+ decimalFormat.format(percentFree*100)+"%" + " less than 30%");
		}
	}
}
